<template>
  <div @click="weixinLogin">
    <m-svg-icon class="w-4 cursor-pointer" name="wexin"></m-svg-icon>
    <div id="weixin"></div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue'
import { getWXLoginData, getWXLoginToken, getWXLoginUserInfo } from '@/api/sys'
import broadcast from './broadcast'
import author from './author.js'

onMounted(() => {})

// 获取当前浏览器地址数据
if (window.location.search) {
  const code = /code=((.*)&state)/.exec(window.location.search)[1]
  if (code) {
    broadcast.sendMessage({ code })
    window.close()
  }
}
/**
 * @params
 * @description 微信登录
 */
const weixinLogin = () => {
  getWXLoginData().then(({ code, data }) => {
    if (code == 200) {
      const { appId, appSecret, redirectUri, scope, state } = data
      window.open(
        `https://open.weixin.qq.com/connect/qrconnect?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`,
        '',
        'height=525,width=585, toolbar=no, menubar=no, scrollbars=no, status=no, location=yes, resizable=yes'
      )
      // 等待用户扫码登录
      broadcast.waitCallBack().then(async ({ code }) => {
        // 关闭通知
        broadcast.destroy()
        // 获取 token
        const { access_token, openid } = await getWXLoginToken({
          appId,
          appSecret,
          code
        })
        // 获取用户信息
        const { nickname, headimgurl } = await getWXLoginUserInfo({
          access_token,
          openid
        })
        author('WX', {
          openid,
          nickname,
          headimgurl
        })
      })
    }
  })
}
</script>
<style scoped lang="scss"></style>
